package com.management.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.management.entity.NewsCommentExample;
import com.management.entity.NewsDetail;
import com.management.entity.NewsDetailExample;
import com.management.mapper.NewsCommentMapper;
import com.management.mapper.NewsDetailMapper;
import com.management.service.NewsDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cd
 * @version 1.0
 * @date 2021/10/7 17:09
 */
@Service
public class NewsDetailServiceImpl implements NewsDetailService {
    NewsCommentMapper newsCommentMapper;
    NewsDetailMapper newsDetailMapper;

    @Autowired
    public void setNewsCommentMapper(NewsCommentMapper newsCommentMapper) {
        this.newsCommentMapper = newsCommentMapper;
    }

    @Autowired
    public void setNewsDetailMapper(NewsDetailMapper newsDetailMapper) {
        this.newsDetailMapper = newsDetailMapper;
    }

    @Override
    public PageInfo<NewsDetail> getNewsDetailPageInfo(int pageNum, int pageSize, String title) {
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 开始查询
        NewsDetailExample newsDetailExample = new NewsDetailExample();
        NewsDetailExample.Criteria criteria = newsDetailExample.createCriteria();
        criteria.andTitleLike("%"+title+"%");
        // 查询
        List<NewsDetail> newsDetails = newsDetailMapper.selectByExample(newsDetailExample);

        PageInfo<NewsDetail> pageInfo = new PageInfo<>(newsDetails);

        return pageInfo;
    }

    @Override
    @Transactional
    public int deleteNewsDetailWithNewsComment(int newsDetailId) {
        // 先删除所有的评论
        NewsCommentExample newsCommentExample = new NewsCommentExample();
        NewsCommentExample.Criteria criteria = newsCommentExample.createCriteria();
        criteria.andNewsIdEqualTo(newsDetailId);
        int deleteCountComment = newsCommentMapper.deleteByExample(newsCommentExample);

        // 删除指定的新闻
        int deleteCountDetail = newsDetailMapper.deleteByPrimaryKey(newsDetailId);
        if (deleteCountDetail == 0) {
            throw new RuntimeException("[ERROR] 删除失败");
        }
        return deleteCountComment+deleteCountDetail;
    }

}
